package com.anxin.act.task.addTask;

import java.util.ArrayList;
import java.util.List;

import com.anxin.act.utils.ActUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.springframework.util.CollectionUtils;


public class ChainedActivitiesCreator extends RuntimeActivityCreatorSupport implements RuntimeActivityCreator {

	/**
	 * 创建节点
	 * @param processEngine
	 * @param processDefinition
	 * @param info
	 * @param type actBefore前加签 actAfter后加签  actEntrustment转签
	 * @return
	 */
	public ActivityImpl[] createActivities(ProcessEngine processEngine, ProcessDefinitionEntity processDefinition,RuntimeActivityDefinitionEntity info,String type) {
		info.setFactoryName(ChainedActivitiesCreator.class.getName());
		RuntimeActivityDefinitionEntityIntepreter radei = new RuntimeActivityDefinitionEntityIntepreter(info);

		if (radei.getCloneActivityIds() == null) {
			radei.setCloneActivityIds((List<String>) CollectionUtils.arrayToList(new String[radei.getAssignees().size()]));
		}

		return createActivities(processEngine, processDefinition, info.getProcessInstanceId(), radei.getPrototypeActivityId(),
				radei.getNextActivityId(), radei.getAssignees(), radei.getCloneActivityIds(),type);
	}

	/**
	 * 创建节点
	 * @param processEngine
	 * @param processDefinition
	 * @param processInstanceId
	 * @param prototypeActivityId
	 * @param nextActivityId
	 * @param assignees
	 * @param activityIds
	 * @param type  actBefore前加签 actAfter后加签  actEntrustment转签
	 * @return
	 */
	private ActivityImpl[] createActivities(ProcessEngine processEngine, ProcessDefinitionEntity processDefinition, String processInstanceId,
			String prototypeActivityId, String nextActivityId, List<String> assignees, List<String> activityIds,String type) {
		//查找当前节点的activiti对象
		ActivityImpl prototypeActivity = ActUtils.getActivityImpl( processDefinition.getId(), prototypeActivityId);

		//根据查找出来的节点创建加签节点，选了多少个审批人，就创建多少个节点
		List<ActivityImpl> activities = new ArrayList<ActivityImpl>();
		for (int i = 0; i < assignees.size(); i++) {
				if (activityIds.get(i) == null) {
					String activityId = createUniqueActivityId(processInstanceId, prototypeActivityId,type);
					activityIds.set(i, activityId);
				}

				ActivityImpl clone = createActivity(processEngine, processDefinition, prototypeActivity, activityIds.get(i), assignees.get(i));
				activities.add(clone);

		}

		ActivityImpl nextActivity = ActUtils.getActivityImpl(processDefinition.getId(), nextActivityId);
		createActivityChain(activities, nextActivity);

		return activities.toArray(new ActivityImpl[0]);
	}
}
